package com.jh.pattern.singleton.threadlocal;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title ThreadLocalSingleton.java
 * @package com.jh.pattern.singleton.threadlocal
 * @description 线程内单例
 * @date 2019-05-23 16:55
 */
public class ThreadLocalSingleton {

    private final static ThreadLocal<ThreadLocalSingleton> instance = new ThreadLocal<ThreadLocalSingleton>(){
        @Override
        protected ThreadLocalSingleton initialValue() {
            return new ThreadLocalSingleton();
        }
    };

    private ThreadLocalSingleton(){}

    public static ThreadLocalSingleton getInstance() {
        return instance.get();
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        }, "Thread1").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
            System.out.println(Thread.currentThread().getName() + "：" + ThreadLocalSingleton.getInstance());
        }, "Thread2").start();

    }

}
